package com.gitee.dolt.swagger2;

import cn.hutool.core.util.StrUtil;
import com.gitee.dolt.base.BaseEnum;
import com.google.common.base.Optional;
import io.swagger.annotations.ApiModelProperty;
import springfox.documentation.schema.Annotations;
import springfox.documentation.service.AllowableListValues;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.swagger.schema.ApiModelProperties;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LYH
 */
public class BaseEnumPropertyPlugin implements ModelPropertyBuilderPlugin {
    @Override
    public void apply(ModelPropertyContext context) {

        Optional<ApiModelProperty> annotation = Optional.absent();

        if (context.getAnnotatedElement().isPresent()) {
            annotation = annotation
                    .or(ApiModelProperties.findApiModePropertyAnnotation(context.getAnnotatedElement().get()));
        }
        if (context.getBeanPropertyDefinition().isPresent()) {
            annotation = annotation.or(Annotations.findPropertyAnnotation(
                    context.getBeanPropertyDefinition().get(),
                    ApiModelProperty.class));
        }

        if (!annotation.isPresent()) {
            return;
        }

        Class<?> rawPrimaryType = context.getBeanPropertyDefinition().get().getRawPrimaryType();
        //过滤得到目标类型
        if (!BaseEnum.class.isAssignableFrom(rawPrimaryType)) {
            return;
        }
        //获取CodedEnum的code值
        BaseEnum[] values = (BaseEnum[]) rawPrimaryType.getEnumConstants();
        List<String> displayValues = Arrays.stream(values).map(codedEnum ->
                StrUtil.format("{}({})", codedEnum.getCode(), codedEnum.getDesc()))
                .collect(Collectors.toList());

        context.getBuilder().allowableValues(new AllowableListValues(displayValues, "LIST"));

    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return true;
    }
}